package com.allm.ai.common.service;

import com.allm.ai.common.entity.ConversationRound;
import com.allm.ai.common.repository.ConversationRoundRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.ArrayList;

@Service
@RequiredArgsConstructor
@Slf4j
public class ConversationRoundService {
    
    private final ConversationRoundRepository roundRepository;
    
    /**
     * 获取对话的下一个轮次编号
     */
    public Integer getNextRoundNumber(String conversationId) {
        return roundRepository.getNextRoundNumber(conversationId);
    }

    /**
     * 创建新的对话轮次占位符（用于并发问答）
     */
    @Transactional
    public ConversationRound createRoundPlaceholder(String conversationId, String userId, String question, List<Long> modelIds) {
        // 获取下一个轮次编号
        Integer nextRoundNumber = getNextRoundNumber(conversationId);
        
        // 判断是否为第一轮
        boolean isFirstRound = nextRoundNumber == 1;
        
        // 将模型ID列表转换为逗号分隔的字符串
        String modelIdsStr = modelIds.stream()
            .map(String::valueOf)
            .collect(Collectors.joining(","));
        
        ConversationRound round = ConversationRound.builder()
            .conversationId(conversationId)
            .userId(userId)
            .roundNumber(nextRoundNumber)
            .question(question)
            .questionSummary(question.length() > 200 ? question.substring(0, 200) + "..." : question)
            .isFirstRound(isFirstRound)
            .modelIds(modelIdsStr) // 直接设置模型ID列表
            .build();
        
        ConversationRound saved = roundRepository.save(round);
        log.info("创建对话轮次占位符: conversationId={}, roundNumber={}, modelIds={}, isFirstRound={}", 
                conversationId, nextRoundNumber, modelIdsStr, isFirstRound);
        
        return saved;
    }
    
    /**
     * 添加模型ID到轮次（支持并发添加）
     */
    @Transactional
    public void addModelToRound(String conversationId, Integer roundNumber, Long modelId) {
        Optional<ConversationRound> roundOpt = roundRepository.findByConversationIdAndRoundNumber(conversationId, roundNumber);
        if (roundOpt.isPresent()) {
            ConversationRound round = roundOpt.get();
            String currentModelIds = round.getModelIds();
            
            // 解析现有模型ID列表
            List<String> modelIdList = currentModelIds == null || currentModelIds.trim().isEmpty() 
                ? List.of() 
                : List.of(currentModelIds.split(","));
            
            // 添加新模型ID（如果不存在）
            String newModelId = String.valueOf(modelId);
            if (!modelIdList.contains(newModelId)) {
                modelIdList = modelIdList.stream()
                    .collect(Collectors.toList());
                modelIdList.add(newModelId);
                
                String updatedModelIds = String.join(",", modelIdList);
                round.setModelIds(updatedModelIds);
                round.setLastMessageAt(LocalDateTime.now());
                roundRepository.save(round);
                
                log.info("添加模型到轮次: conversationId={}, roundNumber={}, modelId={}, modelIds={}", 
                        conversationId, roundNumber, modelId, updatedModelIds);
            }
        }
    }
    
    /**
     * 批量添加模型ID到轮次
     */
    @Transactional
    public void addModelsToRound(String conversationId, Integer roundNumber, List<Long> modelIds) {
        Optional<ConversationRound> roundOpt = roundRepository.findByConversationIdAndRoundNumber(conversationId, roundNumber);
        if (roundOpt.isPresent()) {
            ConversationRound round = roundOpt.get();
            String currentModelIds = round.getModelIds();
            
            // 解析现有模型ID列表
            List<String> existingModelIds = currentModelIds == null || currentModelIds.trim().isEmpty() 
                ? List.of() 
                : List.of(currentModelIds.split(","));
            
            // 添加新模型ID（去重）
            List<String> newModelIds = modelIds.stream()
                .map(String::valueOf)
                .filter(id -> !existingModelIds.contains(id))
                .collect(Collectors.toList());
            
            if (!newModelIds.isEmpty()) {
                List<String> mutableModelIds = new ArrayList<>(existingModelIds);
                mutableModelIds.addAll(newModelIds);
                
                String updatedModelIds = String.join(",", mutableModelIds);
                round.setModelIds(updatedModelIds);
                round.setLastMessageAt(LocalDateTime.now());
                roundRepository.save(round);
                
                log.info("批量添加模型到轮次: conversationId={}, roundNumber={}, modelIds={}", 
                        conversationId, roundNumber, updatedModelIds);
            }
        }
    }
    
    /**
     * 获取轮次使用的模型ID列表
     */
    public List<Long> getRoundModelIds(String conversationId, Integer roundNumber) {
        Optional<ConversationRound> roundOpt = roundRepository.findByConversationIdAndRoundNumber(conversationId, roundNumber);
        if (roundOpt.isPresent()) {
            String modelIds = roundOpt.get().getModelIds();
            if (modelIds != null && !modelIds.trim().isEmpty()) {
                return List.of(modelIds.split(","))
                    .stream()
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            }
        }
        return List.of();
    }
    
    /**
     * 获取对话的所有轮次
     */
    public List<ConversationRound> getConversationRounds(String conversationId) {
        return roundRepository.findByConversationIdOrderByRoundNumberAsc(conversationId);
    }
    
    /**
     * 获取用户的对话摘要列表（用于历史记录）
     */
    public List<ConversationRound> getUserConversationSummaries(String userId) {
        return roundRepository.findUserConversationSummaries(userId);
    }
    
    /**
     * 根据对话ID和轮次编号获取轮次
     */
    public Optional<ConversationRound> getRound(String conversationId, Integer roundNumber) {
        return roundRepository.findByConversationIdAndRoundNumber(conversationId, roundNumber);
    }
    
    /**
     * 获取对话的轮次数量
     */
    public long getRoundCount(String conversationId) {
        return roundRepository.countByConversationId(conversationId);
    }
    
    /**
     * 获取对话摘要（第一轮）
     */
    public Optional<ConversationRound> getConversationSummary(String conversationId) {
        return roundRepository.findByConversationIdAndIsFirstRoundTrue(conversationId);
    }
    
    /**
     * 获取对话的最新轮次编号
     */
    public Integer getLatestRoundNumber(String conversationId) {
        return roundRepository.findMaxRoundNumberByConversationId(conversationId).orElse(1);
    }
    
    /**
     * 删除对话的所有轮次
     */
    @Transactional
    public void deleteConversationRounds(String conversationId) {
        roundRepository.deleteByConversationId(conversationId);
        log.info("删除对话轮次: conversationId={}", conversationId);
    }
    
    /**
     * 停用对话的所有轮次
     */
    @Transactional
    public void deactivateConversationRounds(String conversationId) {
        roundRepository.deactivateByConversationId(conversationId);
        log.info("停用对话轮次: conversationId={}", conversationId);
    }

    /**
     * 获取用户的所有对话ID（去重）
     */
    public List<String> getUserConversationIds(String userId) {
        List<Object[]> results = roundRepository.findUserConversationIdsWithTime(userId);
        return results.stream()
            .map(result -> (String) result[0])
            .collect(Collectors.toList());
    }
}
